<template>
  <div class="question-release-wrapper">
    <van-field v-model="text" type="textarea" placeholder="提问可以选择公开或者私密，公开提问的问题每被偷听一次，你分成￥0.5" rows="5">
      <span class="van-field__counter">{{ counter }}</span>
      <span v-if="reward" class="van-field__price">￥{{ reward }}</span>
      <span v-if="type==2" class="van-field__price">￥{{ master.price }}</span>
    </van-field>
    <image-uploader v-show="type" @imageChanged="updateImages"></image-uploader>
    <div class="items-wrapper">
      <van-cell-group>
        <van-cell v-if="type < 2" title="提问目的" @click="showPurposeAction" :value="purpose ? purpose.name: '选择提问目的'" isLink/>
        <van-cell v-if="type < 2" title="选择作品分类" @click="showCatalogAction" :value="catalog? catalog.name: '选择作品分类'" isLink/>
        <van-cell v-if="type < 2" title="选择点评师等级" @click="showLevelAction" :value="level? level.name: '选择点评师等级'" isLink/>
        <van-cell v-if="type < 2" title="输入您的赏金" @click="showEdit(0)" :value="reward ? reward: rewardPlaceholder" type="number" isLink></van-cell>
        <van-cell title="匿名提问">
          <van-switch v-model="isAnonymous" />
        </van-cell>
      </van-cell-group>
    </div>
    <div class="button-wrapper">
      <button type="button" @click="submit" class="btn btn-yellow">确认发布</button>
    </div>
    <edit-popup :value="editValue" :show-popup="showEditPopup" @confirm="confirmEdit" @cancel="cancelEdit" :placeholder="editPlaceholder"></edit-popup>
    <!--
    <van-actionsheet v-model="catalogActionShow" :actions="catalogActions" />
    -->
    <van-popup v-model="catalogActionShow" position="bottom">
      <van-picker show-toolbar :columns="catalogList" @confirm="pickerConfirm" @cancel="pickerCancel" />
    </van-popup>
    <van-actionsheet v-model="levelActionShow" :actions="levelActions" />
    <van-actionsheet v-model="purposeActionShow" :actions="purposeActions" />
  </div>
</template>

<script>
import Vue from 'vue'
import qs from 'qs'

import request from '@/util/request'
import util from '@/util/util'
import wx from 'weixin-js-sdk'

import { mapGetters } from 'vuex'
import ImageUploader from '@/components/imageUploader'

Vue.component(ImageUploader.name, ImageUploader)

// 发布问题
export default {
  name: 'QuestionRelease',
  data () {
    return {
      type: this.$route.params.type, // 0是提问类型，1是点评类型, 2是请教
      master: this.$route.params.master,
      text: '',
      masterLevel: '高级点评师',
      reward: '',
      rewardPlaceholder: '',
      isAnonymous: false,
      showEditPopup: false,
      editValue: '',
      editPlaceholder: '',
      editIndex: -1,
      editType: 'text',
      images: [],
      catalogs: [],
      levels: [],
      catalog: null,
      level: null,
      catalogActionShow: false,
      levelActionShow: false,
      purposeActionShow: false,
      question: null,
      purpose: null,
      purposeActions: [
        {
          name: '学习提高',
          id: 1,
          callback: this.choosePurpose
        },
        {
          name: '参赛投展',
          id: 2,
          callback: this.choosePurpose
        },
        {
          name: '艺考考级',
          id: 3,
          callback: this.choosePurpose
        },
        {
          name: '鉴赏收藏',
          id: 4,
          callback: this.choosePurpose
        },
        {
          name: '装饰布置',
          id: 5,
          callback: this.choosePurpose
        },
        {
          name: '取消',
          callback: this.cancelAction
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    counter: function() {
      var textCount = this.text.length
      return textCount + '/140'
    },
    /*
    catalogActions: function() {
      var actions = []
      for (var i = 0; i < this.catalogs.length; i++) {
        var catalog = this.catalogs[i]
        var item = {
          id: catalog.id,
          name: catalog.name,
          callback: this.chooseCatalog
        }
        actions.push(item)
      }
      var cancel = { name: '取消', callback: this.cancelAction }
      actions.push(cancel)
      return actions
    },
    */
    catalogList: function() {
      var actions = []
      for (var i = 0; i < this.catalogs.length; i++) {
        var catalog = this.catalogs[i]
        actions.push(catalog.name)
      }
      return actions
    },
    levelActions: function() {
      var levels = []
      for(var i = 0; i < this.levels.length; i++) {
        var le = this.levels[i]
        var item = {
          level: le,
          name: le.name,
          callback: this.chooseLevel
        }
        levels.push(item)
      }
      var cancel = { name: '取消', callback: this.cancelAction }
      levels.push(cancel)
      return levels
    }
  },
  beforeCreate () {
    var webUrl = window.location.href
    var jsApiList = [
       "chooseImage",
       "previewImage",
       "uploadImage",
       "chooseWXPay"
    ]
    if (util.isAndroid()) {
      var that = this
      setTimeout(function() {
        that.SDKRegister(that, webUrl, jsApiList)
      }, 500)
    }
  },
  created () {
    var title = '发布点评'
    if (!this.type) {
      title = '发布问答'
    } else if (this.type == 2) {
      title = '请教'
    }
    window.document.title = title
    this.getCatalogs()
    this.getLevels()
  },
  methods: {
    showEdit(index) {
      if (index == 0) {
        this.editValue = this.reward
        this.editType = 'number'
        
      }
      this.showEditPopup = true
      this.editIndex = index
    },
    confirmEdit(value) {
      this.showEditPopup = false
      if (this.editIndex == 0) {
        this.reward = value
      }
    },
    cancelEdit() {
      this.showEditPopup = false
      this.editIndex = -1
    },
    showCatalogAction() {
      this.catalogActionShow = !this.catalogActionShow
    },
    /*
    chooseCatalog(item) {
      this.catalog = item
      this.catalogActionShow = false
    },
    */
    pickerConfirm(value, index) {
      this.catalog = this.catalogs[index]
      this.catalogActionShow = false
    },
    pickerCancel() {
      this.catalogActionShow = false
    },
    showLevelAction() {
      this.levelActionShow = !this.levelActionShow
    },
    chooseLevel(item) {
      this.level = item.level
      var level = item.level
      this.levelActionShow = false
      if (this.type == 0) {
        console.log(item)
        if (level.low_price_wd && level.high_price_wd) {
          this.rewardPlaceholder = '要求￥' + level.low_price_wd + '~￥' + level.high_price_wd
          this.editPlaceholder = '输入您的赏金，' + this.rewardPlaceholder
        } else if (level.low_price_wd && !level.high_price_wd) {
          this.rewardPlaceholder = '要求>=￥' + level.low_price_wd
          this.editPlaceholder = '输入您的赏金，' + this.rewardPlaceholder
        } else if (!level.low_price_wd && level.high_price_wd) {
          this.rewardPlaceholder = '要求<=￥' + level.high_price_wd
          this.editPlaceholder = '输入您的赏金，' + this.rewardPlaceholder
        }
      } else if (this.type == 1) {
        if (level.low_price_dp && level.high_price_dp) {
          this.rewardPlaceholder = '要求￥' + level.low_price_dp + '~￥' + level.high_price_dp
          this.editPlaceholder = '输入您的赏金，' + this.rewardPlaceholder
        } else if (level.low_price_dp && !level.high_price_dp) {
          this.rewardPlaceholder = '要求>=￥' + level.low_price_dp
          this.editPlaceholder = '输入您的赏金，' + this.rewardPlaceholder
        } else if (!level.low_price_dp && level.high_price_dp) {
          this.rewardPlaceholder = '要求<=￥' + level.high_price_dp
          this.editPlaceholder = '输入您的赏金，' + this.rewardPlaceholder
        }
      }
    },
    showPurposeAction() {
      this.purposeActionShow = !this.purposeActionShow
    },
    choosePurpose(item) {
      this.purpose = item
      this.purposeActionShow = false
    },
    cancelAction() {
      this.catalogActionShow = false
      this.levelActionShow = false
      this.purposeActionShow = false
    },
    getCatalogs: function() {
      if (this.$store.getters.questionCatalogs.length) {
        this.catalogs = this.$store.getters.questionCatalogs
      }
    },
    getLevels: function() {
      var that = this
      if (this.$store.getters.masterLevels.length) {
        this.levels = this.$store.getters.masterLevels
      } else {
        request.getLevels(function(err, res) {
          if (!err) {
            that.levels = res.results
            var payload = {
              levels: that.levels
            }
            that.$store.dispatch('getMasterLevels', payload)
          }
        })
      }
    },
    payReward: function(question, callback) {
      var that = this
      var params = {
        type: 0, // 0：提问，1：偷听，2：充值
        amount: this.reward,
        object_id: question.id
      }
      if (this.type == 2) {
        params.amount = this.master.price
      }
      this.axios.post('/finances/pay/', qs.stringify(params))
      .then(function (res) {
        if (res.status >= 200 && res.status < 300) {
          if (!res.data.pay_type) {
            // 使用余额支付成功
            // 减少balance
            var payload = {
              amount: parseFloat(params.amount)
            }
            that.$store.dispatch('payBalance', payload)
            return callback(null)
          }
          console.log(res.data)
          var payInfo = res.data.pay_info
          var timeStamp = payInfo.timeStamp.toString()
          that.wx.chooseWXPay({
            timestamp: timeStamp, 
            nonceStr: payInfo.nonceStr,
            package: payInfo.package,
            signType: payInfo.signType,
            paySign: payInfo.paySign,
            success: function (res) {
              console.log(res)
              // 支付成功后的回调函数
              that.canPlay = true
              return callback(null)
            },
            fail: function (res) {
              console.log(res)
              return callback(res)
            }
          });
        }
      })
      .catch(function (error) {
        return callback(error)
      })
    },
    tryPay(question) {
      var that = this
      this.payReward(question, function(error) {
        if (!error) {
          that.$toast.success('问题发布成功')
          return that.$router.go('-1')
        } else {
          that.$dialog.confirm({
            title: '提示', message: '支付失败，是否继续支付？'
          }).then(() => {
            return that.tryPay(question)
          }).catch(() => {
            // 确定放弃，退出当前页面
            return that.$router.go('-1')
          })
        }
      })
    },
    submit() {
      if (this.question) {
        if (this.reward > this.userInfo.balance) {
          return that.tryPay(this.question)
        } else {
          return this.$dialog.confirm({
            title: '支付提醒',
            message: '使用余额支付提问的费用？'
          }).then(() => {
            return this.tryPay(this.question)
          }).catch(() => {
            return
          })
        }
      }
      if (!this.text) {
        return this.$toast.fail('文字内容不能为空')
      }
      if (this.type != 2) {
        if (!this.purpose) {
          return this.$toast.fail('请选择提问目的')
        }
        if (!this.catalog) {
          return this.$toast.fail('请选择作品分类')
        }
        if (!this.level) {
          return this.$toast.fail('请选择点评师等级')
        }
        if (!this.reward) {
          return this.$toast.fail('请输入赏金数')
        }
        if (this.type == 0) {
          if (this.reward < this.level.low_price_wd || (this.reward > this.level.high_price_wd && this.level.high_price_wd > 0))  {
            return this.$toast.fail('赏金金额不在有效区间')
          } 
        } else if(this.type == 1) {
          if (this.reward < this.level.low_price_dp || (this.reward > this.level.high_price_dp && this.level.high_price_dp > 0))  {
            return this.$toast.fail('赏金金额不在有效区间')
          }
        }
      }
      if (this.type && !this.images.length) {
        return this.$toast.fail('请上传您的作品照片')
      }
    
      var mediaIds = []
      this.images.forEach(function(img) {
        mediaIds.push(img.serverId)
      })
      var media_ids = mediaIds.join(',')
      var params = {
        'type': this.type,
        'text': this.text,
        'is_public': !this.isAnonymous,
        'media_ids': media_ids,
      }
      if (this.type == 2) {
        params.reward = this.master.price
        params.replier = this.master.id
        params.master_level = this.master.level.id
      } else {
        params.reward = this.reward
        params.purpose = this.purpose.name
        params.catalog = this.catalog.id
        params.master_level = this.level.id
      }
      this.$toast.loading()
      var that = this
      // 调用登陆接口
      this.axios.post('/dianping/question/', qs.stringify(params))
      .then(function (res) {
        that.$toast.clear()
        if (res.status >= 200 && res.status < 300) {
          console.log(res.data)
          that.question = res.data
          // 发布成功，请求微信支付
          if (that.reward > that.userInfo.balance) {
            that.tryPay(res.data)
          } else {
            return that.$dialog.confirm({
              title: '支付提醒',
              message: '使用余额支付提问的费用？'
            }).then(() => {
              return that.tryPay(res.data)
            }).catch(() => {
              return
            })
          }
        } else {
          return that.$toast.fail(res.msg)
        }
      })
      .catch(function (error) {
        that.$toast.clear()
        if (error.response) {
          that.$toast.fail(error.response.data.detail)
        } else {
          that.$toast.fail('请求出错')
        }
      })
    },
    updateImages(images) {
      // 更新图片文件列表
      this.images = images
    }
  }
}

</script>
